package com.example.mybatisplusdemo.service.decorator;

import com.example.mybatisplusdemo.model.domain.Flight;
import com.example.mybatisplusdemo.model.domain.ItineraryRequest;
import com.example.mybatisplusdemo.service.FlightSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SmartRecommendationDecorator {

    private final FlightSearchService flightSearchService;

    @Autowired
    public SmartRecommendationDecorator(FlightSearchService flightSearchService) {
        this.flightSearchService = flightSearchService;
    }

    public List<Flight> recommendWithSmartRanking(ItineraryRequest request) {
        // 1. 获取基础搜索结果
        List<Flight> flights = flightSearchService.searchFlights(request);

        // 2. 应用智能排序算法
        return flights.stream()
                .sorted(getSmartComparator())
                .collect(Collectors.toList());
    }

    private Comparator<Flight> getSmartComparator() {
        return Comparator
                // 综合推荐指数（倒序）
                .comparing(this::calculateRecommendationIndex).reversed()
                // 次要排序条件
                .thenComparing(Flight::getPrice)
                .thenComparing(f -> Duration.between(
                        f.getDepartureTime(),
                        f.getArrivalTime()).toMinutes());
    }

    private double calculateRecommendationIndex(Flight flight) {
        // 智能推荐算法（可根据业务需求调整权重）
        return flight.getPunctualityRate().doubleValue() * 0.3 +  // 准点率
                flight.getSeatComfort().doubleValue() * 0.25 +    // 座位舒适度
                flight.getUserRating().doubleValue() * 0.2 +      // 用户评分
                (1 - flight.getCarbonEmission().doubleValue()/500) * 0.15 + // 碳排放
                (flight.getWifiAvailable() ? 0.1 : 0);             // WiFi可用性
    }
}